package models

import "gorm.io/gorm"

type Goods struct {
	gorm.Model
	Title      string  //名称标题
	Taste      string  //口味
	Ingredient string  //配料
	Price      float64 //价格
	Stock      int64   //库存
	ImageUrl   string  //图片地址
	Likes      int64   //热度
}

func (g *Goods) GetGoodsById(goodsId int64) error {
	return DB.Where("id=?", goodsId).Limit(1).Find(&g).Error
}

func (g *Goods) CreateGoods() error {
	return DB.Create(&g).Error
}

// 商品检索方法封装
func (g *Goods) SearchGoods(title, sortWord, taste, order string,
	page, pageSize int, minPrice, maxPrice float64) (listGoods []*Goods, err error) {
	query := DB
	if title != "" {
		query = query.Where("title like ?", "%"+title+"%")
	}

	if taste != "" {
		query = query.Where("taste like ?", "%"+taste+"%")
	}

	if minPrice != 0 && maxPrice != 0 {
		query = query.Where("price between ? and ?", minPrice, maxPrice)
	}

	if order != "" {
		if order == "asc" {
			if sortWord == "likes" {
				query = query.Order("likes asc")
			} else if sortWord == "price" {
				query = query.Order("price asc")
			} else {
				query = query.Order("created_at asc")
			}
		} else {
			if sortWord == "likes" {
				query = query.Order("likes desc")
			} else if sortWord == "price" {
				query = query.Order("price desc")
			} else {
				query = query.Order("created_at desc")
			}
		}
	}

	err = query.Scopes(Paginate(page, pageSize)).
		Find(&listGoods).Error
	return
}

// 分页方法封装
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
